// 在 WXML 文件对应的 JS 文件中编写
Page({
    data: {
        wordArray: [],
        wordRead: ["堂听顺序："],
        overlayVisible: false,
        startButtonText: " 开始堂听",
        loadingText: "",
        wordReadText: "",
        running: false,
        showMask: false,
        showModal: false,
        begin: true,
        welcome: false,
    },

    onLoad: function () {
        let app = getApp();
        let score = app.globalData.score;
        console.log("全局积分：" + score);
        if (!app.globalData.firstLogin) {
            app.globalData.firstLogin = true;
            app.globalData.score += 10;
            tt.showToast({
                title: '首次登录，赠送10分',
                icon: 'success', // 隐藏默认图标
                duration: 1500, // 设置显示时长，根据单词长度调整
                mask: true,
            });
        }
        this.page = this; // 保存页面对象的引用
        let readHistory = tt.getStorageSync('readHistory');
        if (readHistory && readHistory.trim() !== '') {
            this.setData({wordArray: readHistory.split(',')});
        }
        tt.setStorageSync('readHistory', "");
        this.createButtons();
        tt.showShareMenu({
            // 设置是否使用带 shareTicket 的转发，默认为 false，即不使用
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline']
        });
    },

    createButtons: function () {
        const buttons = this.data.wordArray.map((word) => {
            return {text: word, disabled: false, played: false};
        });
        this.setData({buttons: buttons});
    },

    startPlaying: function () {
        if (this.data.running) {
            tt.showToast({
                title: '已经在堂听中！', // 将要朗读的单词内容
                icon: 'none', // 隐藏默认图标
                duration: 1000 // 设置显示时长，根据单词长度调整
            });
            return;
        }

        //初始化
        const buttons = this.data.buttons;

        for (let i = 0; i < buttons.length; i++) {
            buttons[i].played = false;
        }
        this.setData({
            buttons: buttons,
            wordReadText: "",
            running: true,
            showMask: true,
            wordRead: ["堂听顺序："]
        });

        // 从本地缓存中读取数据
        let historyList = tt.getStorageSync('historyList') || [];
        // 判断是否已经存在3条记录，如果是，则删除最旧的第一条记录
        if (historyList.length >= 3) {
            historyList.shift(); // 删除数组的第一个元素
        }
        // 添加新的记录到数组中
        historyList.push(this.data.wordArray.join(", "));
        // 将更新后的数组存储回本地缓存中
        tt.setStorageSync('historyList', historyList);


        this.sendTextToBackend('kaishitangting');

        var that = this;
        var index = 0;
        var times = 5;
        var remainingTime = times;
        var readText = "";
        if (index == 0) {
            remainingTime = 2;
        }
        let readArray = that.shuffleArray(that.data.wordArray);
        var interval = setInterval(() => {// 使用箭头函数保持正确的 this 指向
            if (index < readArray.length) {
                if (remainingTime == 0) {
                    var word = readArray[index];
                    index++;
                    remainingTime = times;
                    const newWordRead = that.data.wordRead.concat(index + " " + word);
                    that.setData({
                        wordRead: newWordRead
                    });
                    this.sendTextToBackend(word);
                }

                that.setData({
                    countdown: remainingTime,
                    startButtonText: "堂听中 " + remainingTime,
                    loadingText: remainingTime + " 秒后播放下个单词"
                });
                remainingTime--;
            } else {
                clearInterval(interval);
                that.setData({
                    startButtonText: "再次堂听",
                    running: false,
                    loadingText: "",
                    showMask: false,
                    showModal: true
                });
            }
        }, 1000);
    },

    shuffleArray: function (array) {
        for (let i = array.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [array[i], array[j]] = [array[j], array[i]];
        }
        return array;
    },

    speakWord: function (word) {
        var that = this;
        var speek = 2;

        tt.showToast({
            title: word,
            icon: 'none'
        });

        setInterval(function () {
            if (speek == 0) {
                return;
            }
            tt.showToast({
                title: word,
                icon: 'none'
            });
            speek--;
        }, 1600);
    },

    chooseImage: function () {
        let app = getApp();
        let score = app.globalData.score;
        if (score >= 1) {

        } else {
            tt.showToast({
                title: '分数不足！',
                icon: 'fail', // 隐藏默认图标
                duration: 1500, // 设置显示时长，根据单词长度调整
                mask: true,
            });
            return;
        }
        var that = this;
        that.setData({
            overlayVisible: true
        });
        tt.chooseImage({
            count: 1,
            success: function (res) {
                const tempFilePaths = res.tempFilePaths;
                const tempFilePath = tempFilePaths[0];

                // 压缩图片
                tt.compressImage({
                    src: tempFilePath, // 图片文件路径
                    quality: 20, // 压缩质量，范围为 1-100，默认为80
                    success(res) {
                        const compressedFilePath = res.tempFilePath;
                        console.log('压缩后的照片路径：', compressedFilePath);
                        tt.uploadFile({
                            url: 'https://uu.artcodes.ltd/ocr/uploadImage',
                            filePath: compressedFilePath,
                            name: 'file',
                            success: function (res) {
                                var wordArray = JSON.parse(res.data);
                                that.setData({
                                    wordArray: wordArray
                                });
                                that.createButtons();
                            },
                            complete: function () {
                                that.setData({
                                    overlayVisible: false
                                });
                            }
                        });
                        app.globalData.score -= 1;
                        this.setData({
                            score: app.globalData.score,
                        });
                        // 在这里可以将压缩后的照片上传或进行其他操作
                    },
                    fail(error) {
                        console.error('压缩照片失败：', error);
                    }
                });


                // var tempFilePaths = res.tempFilePaths;
                // console.log("chooseImage 返回结果：", res);

            },
            fail: function (err) {
                let errType = err.errMsg.includes("chooseImage:fail cancel")
                    ? "取消选择"
                    : "选择失败";
                tt.showModal({
                    title: errType,
                    content: err.errMsg,
                    showCancel: false,
                });
                that.setData({
                    overlayVisible: false
                });
            }
        });
    },
    createWordCard: function (word) {
        if (this.data.running) {
            tt.showToast({
                title: '堂听结束后才能添加单词。', // 将要朗读的单词内容
                icon: 'none', // 隐藏默认图标
                duration: 1000 // 设置显示时长，根据单词长度调整
            });
            return;
        }
        // 创建单词卡片组件
        return {
            tagName: 'view',
            id: 'word-' + word,
            class: 'word-card',
            children: [{
                type: 'text',
                text: word
            }]
        };
    },
    deleteWord: function (e) {
        const index = e.currentTarget.dataset.index;
        const newButtons = this.data.buttons.filter((item, idx) => idx !== index);
        const newWordArray = this.data.wordArray.filter((item, idx) => idx !== index);
        this.setData({
            buttons: newButtons,
            wordArray: newWordArray
        });
    },
    showInput: function () {
        if (this.data.running) {
            tt.showToast({
                title: '堂听结束后才能添加单词。', // 将要朗读的单词内容
                icon: 'none', // 隐藏默认图标
                duration: 1000 // 设置显示时长，根据单词长度调整
            });
            return;
        }
        var that = this;
        tt.showModal({
            title: '添加单词',
            content: '',
            showCancel: true,
            confirmText: '确定',
            cancelText: '取消',
            editable: true,
            input: true,
            success: function (res) {
                if (res.confirm) {
                    const newWord = res.content.trim();
                    if (newWord !== '') {
                        const newButtons = that.data.buttons.concat({text: newWord, disabled: false, played: false});
                        const newWordArray = that.data.wordArray.concat(newWord);
                        that.setData({
                            buttons: newButtons,
                            wordArray: newWordArray
                        });
                    }
                }
            }
        });
    },
    closeModal() {
        // 关闭弹出框时，执行动画使其慢慢滑回
        this.animateSidebar(0, () => {
            this.setData({
                showModal: false
            });
        });
    },
    animateSidebar(offset, callback) {
        const animation = tt.createAnimation({
            duration: 2500, // 动画时长为 500ms
            timingFunction: 'ease'
        });
        animation.right(offset).step();

        this.setData({
            sidebarAnimation: animation.export() // 将动画数据绑定到视图中
        });

        // 如果传入了回调函数，则在动画执行完毕后执行回调
        if (callback && typeof callback === 'function') {
            setTimeout(callback, 500);
        }
    },

    mylisting() {
        tt.showToast({
            title: '堂听结束后才能添加单词。', // 将要朗读的单词内容
            icon: 'none', // 隐藏默认图标
            duration: 1000 // 设置显示时长，根据单词长度调整
        });
        // 在 js 文件中
        tt.redirectTo({
            url: 'my'
        });
    },

    sendTextToBackend: function (text) {
        const innerAudioContext = tt.createInnerAudioContext();
        innerAudioContext.autoplay = true;
        //innerAudioContext.src = "https://uuenglishclub.oss-cn-guangzhou.aliyuncs.com/Eva-where.mp3"; // 使用dataURL直接播放音频数据
        innerAudioContext.src = "https://uu.artcodes.ltd/genVoiceMp3?text=" + text;
        innerAudioContext.play();
        innerAudioContext.onError((error) => {
            tt.showModal({
                title: "播放出错",
                content: `详细错误信息：${error.errMsg}`,
            });
            console.log("播放出错", error);
        });
        // tt.request({
        //   url: "https://uu.artcodes.ltd/genVoice?text=" + text,
        //   method: 'GET',
        //   success: function (res) {
        //     // 将 ArrayBuffer 转换成 Base64 字符串
        //     const base64AudioContent = res.data;

        //     // 播放后端返回的音频文件
        //     const backgroundAudioManager = tt.getBackgroundAudioManager();
        //     backgroundAudioManager.title = text;
        //     backgroundAudioManager.epname = text;
        //     backgroundAudioManager.src = base64AudioContent; // 使用dataURL直接播放音频数据
        //     backgroundAudioManager.play();
        //   },
        //   fail: function (err) {
        //     tt.showToast({
        //       title: err, // 将要朗读的单词内容
        //       icon: 'none', // 隐藏默认图标
        //       duration: 1000 // 设置显示时长，根据单词长度调整
        //     });
        //   }
        // });
    },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {
        return {
            title: '好友推荐，立享特权！尽情畅听！',
            imageUrl: "logo.jpg",
            path: ''
        };
    },
    // 点击分享按钮时执行
    onShareAppMessage: function () {
        // 返回自定义的分享内容
        return {
            title: '好友推荐，立享特权！尽情畅听',
            path: '', // 分享页面的路径
            imageUrl: 'logo.jpg' // 分享图片的路径
        };
    }

});